package com.selfdriving;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.Reference;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;
import android.app.Application;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.MKGeneralListener;
import com.baidu.mapapi.map.MKEvent;
import com.baidu.mapapi.search.MKAddrInfo;
import com.baidu.mapapi.search.MKBusLineResult;
import com.baidu.mapapi.search.MKDrivingRouteResult;
import com.baidu.mapapi.search.MKGeocoderAddressComponent;
import com.baidu.mapapi.search.MKPoiResult;
import com.baidu.mapapi.search.MKSearch;
import com.baidu.mapapi.search.MKSearchListener;
import com.baidu.mapapi.search.MKShareUrlResult;
import com.baidu.mapapi.search.MKSuggestionResult;
import com.baidu.mapapi.search.MKTransitRouteResult;
import com.baidu.mapapi.search.MKWalkingRouteResult;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.selfdriving.bean.Entity;
import com.selfdriving.bean.Home;
import com.selfdriving.bean.MyArticleDetails;
import com.selfdriving.bean.MyGroups;
import com.selfdriving.bean.NearByPeople;
import com.selfdriving.bean.ScenicSpots;
import com.selfdriving.bean.User;
import com.selfdriving.utils.Constant;
import com.selfdriving.utils.PhoneInfo;
import com.selfdriving.utils.SystemSettings;

public class BaseApplication extends Application
{
	public static final String CURRENT_CITY_ID = "101240203";

	public final static String strKey = "2E8PXwI7dbsbrTqlt23Wlt9D";
	public LocationClient mLocClient;
	public BMapManager mBMapManager = null;
	public double mLongitude = 0;// 经度
	public double mLatitude = 0;// 纬度
	public String city = "未定位到城市";// 用户所在城市
	private MKSearch mSearch = null;// 反地理编码查询
	boolean isflag = true;
	public int index = 1;
	public String mUploadPhotoPath;// 相册路径
	public GeoPoint geoPoint = null;
	public List<Home> homeList = new ArrayList<Home>();
	public GeoPoint myPoint = null;
	public ArrayList<ScenicSpots> ScenicarrayList = new ArrayList<ScenicSpots>();
	public Map<String, SoftReference<Bitmap>> mAvatarCache = new HashMap<String, SoftReference<Bitmap>>();
	public List<Map<String, Object>> myFriends = new ArrayList<Map<String, Object>>();
	public List<NearByPeople> mNearByPeoples = new ArrayList<NearByPeople>();
	public List<MyGroups> myGroupsList = new ArrayList<MyGroups>();
	private Bitmap mDefaultAvatar;
	private static final String AVATAR_DIR = "avatar/";
	public static final String imageCache = Environment
			.getExternalStorageDirectory() + "/Driving/cache";
	public Map<String, SoftReference<Bitmap>> mPhotoThumbnailCache = new HashMap<String, SoftReference<Bitmap>>();
	private static final String PHOTO_THUMBNAIL_DIR = "photo/thumbnail/";
	public static List<String> mEmoticons = new ArrayList<String>();
	public static Map<String, Integer> mEmoticonsId = new HashMap<String, Integer>();
	public static List<String> mEmoticons_Zem = new ArrayList<String>();
	public static List<String> mEmoticons_Zemoji = new ArrayList<String>();
	public Map<String, SoftReference<Bitmap>> mStatusPhotoCache = new HashMap<String, SoftReference<Bitmap>>();
	private static final String STATUS_PHOTO_DIR = "statusphoto/";
	public Map<String, SoftReference<Bitmap>> mPhotoOriginalCache = new HashMap<String, SoftReference<Bitmap>>();
	private static final String PHOTO_ORIGINAL_DIR = "photo/original/";
	public ImageLoader imageLoader = ImageLoader.getInstance();
	public DisplayImageOptions options;
	public User user;// 当前登录用户
	public MyArticleDetails myArticleDetails;
	public String viewImg[];

	public List<Entity> togetherList = new ArrayList<Entity>();
	public List<Entity> nearFriendsList = new ArrayList<Entity>();
	public List<Entity> listHotel = new ArrayList<Entity>();
	public List<Entity> listEat = new ArrayList<Entity>();
	public List<Entity> listBuy = new ArrayList<Entity>();
	public boolean exit = true;
	public int intFlag = 0;

	@Override
	public void onCreate()
	{
		super.onCreate();
		initEngineManager(this);
		mSearch = new MKSearch();
		mSearch.init(mBMapManager, new MKSearchListener()
		{
			@Override
			public void onGetAddrResult(MKAddrInfo res, int error)
			{
				if (error != 0)
				{
					String str = String.format("错误号：%d", error);
					Toast.makeText(BaseApplication.this, str, Toast.LENGTH_LONG)
							.show();
					return;
				}
				if (res.type == MKAddrInfo.MK_REVERSEGEOCODE)
				{
					String addr = res.strAddr;
					System.out.println(addr);
					MKGeocoderAddressComponent addrInfo = res.addressComponents;
					String city = addrInfo.city;
					BaseApplication.this.city = city;
					System.out.println(city);
					installCalculate();
				}
			}

			@Override
			public void onGetBusDetailResult(MKBusLineResult arg0, int arg1)
			{
			}

			@Override
			public void onGetDrivingRouteResult(MKDrivingRouteResult arg0,
					int arg1)
			{
			}

			@Override
			public void onGetPoiDetailSearchResult(int arg0, int arg1)
			{
			}

			@Override
			public void onGetPoiResult(MKPoiResult arg0, int arg1, int arg2)
			{
			}

			@Override
			public void onGetShareUrlResult(MKShareUrlResult arg0, int arg1,
					int arg2)
			{
			}

			@Override
			public void onGetSuggestionResult(MKSuggestionResult arg0, int arg1)
			{
			}

			@Override
			public void onGetTransitRouteResult(MKTransitRouteResult arg0,
					int arg1)
			{
			}

			@Override
			public void onGetWalkingRouteResult(MKWalkingRouteResult arg0,
					int arg1)
			{
			}

		});
		mDefaultAvatar = BitmapFactory.decodeResource(getResources(),
				R.drawable.ic_common_def_header);
		for (int i = 1; i < 64; i++)
		{
			String emoticonsName = "[zem" + i + "]";
			int emoticonsId = getResources().getIdentifier("zem" + i,
					"drawable", getPackageName());
			mEmoticons.add(emoticonsName);
			mEmoticons_Zem.add(emoticonsName);
			mEmoticonsId.put(emoticonsName, emoticonsId);
		}
		for (int i = 1; i < 59; i++)
		{
			String emoticonsName = "[zemoji" + i + "]";
			int emoticonsId = getResources().getIdentifier("zemoji_e" + i,
					"drawable", getPackageName());
			mEmoticons.add(emoticonsName);
			mEmoticons_Zemoji.add(emoticonsName);
			mEmoticonsId.put(emoticonsName, emoticonsId);
		}
		// 获取当前用户位置
		mLocClient = new LocationClient(getApplicationContext());
		mLocClient.setAK(strKey);
		mLocClient.registerLocationListener(new BDLocationListener()
		{

			@Override
			public void onReceivePoi(BDLocation location)
			{

			}

			@Override
			public void onReceiveLocation(final BDLocation location)
			{
				mLongitude = location.getLongitude();
				mLatitude = location.getLatitude();
				myPoint = new GeoPoint((int) (mLatitude * 1e6),
						(int) (mLongitude * 1e6));
				System.out.println("地理位置" + "经度:" + mLongitude + ",纬度:"
						+ mLatitude);
				mSearch.reverseGeocode(myPoint);
				mLocClient.stop();
			}
		});
		mLocClient.start();
		mLocClient.requestOfflineLocation();
		System.out.println("开始获取");
		initImageLoader(this);
	}

	public void initImageLoader(Context context)
	{
		String st = Environment.getExternalStorageDirectory() + "/Drive/Cache";
		File f = new File(st);
		if (!f.exists())
		{
			f.mkdir();
		}
		File cacheDir = new File(st);
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
				context).threadPriority(Thread.NORM_PRIORITY - 2)
				.denyCacheImageMultipleSizesInMemory()
				.discCache(new UnlimitedDiscCache(cacheDir))
				.discCacheFileNameGenerator(new Md5FileNameGenerator())
				.tasksProcessingOrder(QueueProcessingType.LIFO).build();
		ImageLoader.getInstance().init(config);
		options = new DisplayImageOptions.Builder()
				.showImageOnLoading(R.drawable.default_loading)
				.showImageForEmptyUri(R.drawable.default_loading)
				.showImageOnFail(R.drawable.default_loading)
				.bitmapConfig(Bitmap.Config.RGB_565).cacheInMemory(true)
				.cacheOnDisc(true).build();
	}

	@Override
	public void onLowMemory()
	{
		super.onLowMemory();
		Log.e("BaseApplication", "onLowMemory");
	}

	@Override
	public void onTerminate()
	{
		super.onTerminate();
		Log.e("BaseApplication", "onTerminate");
	}

	public void initEngineManager(Context context)
	{
		if (mBMapManager == null)
		{
			isflag = true;
			mBMapManager = new BMapManager(context);
		}

		if (!mBMapManager.init(strKey, new MyGeneralListener(
				BaseApplication.this.getApplicationContext())))
		{
			isflag = false;
			Toast.makeText(BaseApplication.this.getApplicationContext(),
					"BMapManager  初始化错误!", Toast.LENGTH_LONG).show();
		}
		mBMapManager.start();
	}

	// 常用事件监听，用来处理通常的网络错误，授权验证错误等
	public static class MyGeneralListener implements MKGeneralListener
	{
		Context context;

		public MyGeneralListener(Context context)
		{
			this.context = context;
		}

		@Override
		public void onGetNetworkState(int iError)
		{
			if (iError == MKEvent.ERROR_NETWORK_CONNECT)
			{
				showLongToast(context, "您的网络出错啦！");
			} else if (iError == MKEvent.ERROR_NETWORK_DATA)
			{
				showLongToast(context, "输入正确的检索条件！");
			}
		}

		@Override
		public void onGetPermissionState(int iError)
		{
			if (iError == MKEvent.ERROR_PERMISSION_DENIED)
			{
				// 授权Key错误：

				showLongToast(context, "请在 ApplicationConfig.java文件输入正确的授权Key！");
			}
		}

	}

	/** 长时间显示Toast提示(来自String) **/
	public static void showLongToast(Context context, String text)
	{
		Toast.makeText(context, text, Toast.LENGTH_LONG).show();
	}

	/** 长时间显示Toast提示(来自String) **/
	public void showShortToast(Context context, String text)
	{
		Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
	}

	public Bitmap getAvatar(String imageName)
	{
		if (mAvatarCache.containsKey(imageName))
		{
			Reference<Bitmap> reference = mAvatarCache.get(imageName);
			if (reference.get() == null || reference.get().isRecycled())
			{
				mAvatarCache.remove(imageName);
			} else
			{
				return reference.get();
			}
		}
		InputStream is = null;
		Bitmap bitmap = null;
		try
		{
			is = getAssets().open(AVATAR_DIR + imageName);
			bitmap = BitmapFactory.decodeStream(is);
			if (bitmap == null)
			{
				throw new FileNotFoundException(imageName + "is not find");
			}
			mAvatarCache.put(imageName, new SoftReference<Bitmap>(bitmap));
			return bitmap;
		} catch (Exception e)
		{
			return mDefaultAvatar;
		} finally
		{
			try
			{
				if (is != null)
				{
					is.close();
					is = null;
				}
			} catch (IOException e)
			{

			}
		}
	}

	public Bitmap getPhotoThumbnail(String imageName)
	{
		if (mPhotoThumbnailCache.containsKey(imageName))
		{
			Reference<Bitmap> reference = mPhotoThumbnailCache.get(imageName);
			if (reference.get() == null || reference.get().isRecycled())
			{
				mPhotoThumbnailCache.remove(imageName);
			} else
			{
				return reference.get();
			}
		}
		InputStream is = null;
		Bitmap bitmap = null;
		try
		{
			is = getAssets().open(PHOTO_THUMBNAIL_DIR + imageName);
			bitmap = BitmapFactory.decodeStream(is);
			if (bitmap == null)
			{
				throw new FileNotFoundException(imageName + "is not find");
			}
			mPhotoThumbnailCache.put(imageName, new SoftReference<Bitmap>(
					bitmap));
			return bitmap;
		} catch (Exception e)
		{
			return null;
		} finally
		{
			try
			{
				if (is != null)
				{
					is.close();
					is = null;
				}
			} catch (IOException e)
			{

			}
		}
	}

	public Bitmap getStatusPhoto(String imageName)
	{
		if (mStatusPhotoCache.containsKey(imageName))
		{
			Reference<Bitmap> reference = mStatusPhotoCache.get(imageName);
			if (reference.get() == null || reference.get().isRecycled())
			{
				mStatusPhotoCache.remove(imageName);
			} else
			{
				return reference.get();
			}
		}
		InputStream is = null;
		Bitmap bitmap = null;
		try
		{
			is = getAssets().open(STATUS_PHOTO_DIR + imageName);
			bitmap = BitmapFactory.decodeStream(is);
			if (bitmap == null)
			{
				throw new FileNotFoundException(imageName + "is not find");
			}
			mStatusPhotoCache.put(imageName, new SoftReference<Bitmap>(bitmap));
			return bitmap;
		} catch (Exception e)
		{
			return null;
		} finally
		{
			try
			{
				if (is != null)
				{
					is.close();
					is = null;
				}
			} catch (IOException e)
			{

			}
		}
	}

	public Bitmap getPhotoOriginal(String imageName)
	{
		if (mPhotoOriginalCache.containsKey(imageName))
		{
			Reference<Bitmap> reference = mPhotoOriginalCache.get(imageName);
			if (reference.get() == null || reference.get().isRecycled())
			{
				mPhotoOriginalCache.remove(imageName);
			} else
			{
				return reference.get();
			}
		}
		InputStream is = null;
		Bitmap bitmap = null;
		try
		{
			is = getAssets().open(PHOTO_ORIGINAL_DIR + imageName);
			bitmap = BitmapFactory.decodeStream(is);
			if (bitmap == null)
			{
				throw new FileNotFoundException(imageName + "is not find");
			}
			mPhotoOriginalCache.put(imageName,
					new SoftReference<Bitmap>(bitmap));
			return bitmap;
		} catch (Exception e)
		{
			return null;
		} finally
		{
			try
			{
				if (is != null)
				{
					is.close();
					is = null;
				}
			} catch (IOException e)
			{

			}
		}
	}

	/** 统计安装量 */
	public void installCalculate()
	{
		boolean isInstall = SystemSettings.getBoolean(getApplicationContext(),
				"isInstall");
		if (isInstall)
		{// 第一次启动执行
			isInstall = false;
			PhoneInfo device = new PhoneInfo(this);
			String imei = device.getIMEI();
			String imsi = device.getIMSI();
			FinalHttp fh = new FinalHttp();
			AjaxParams ajaxParams = new AjaxParams();
			ajaxParams.put("imei", imei);
			ajaxParams.put("imsi", imsi);
			ajaxParams.put("city", city);
			ajaxParams.put("f", "11");
			fh.post(Constant.POST, ajaxParams, new AjaxCallBack<Object>()
			{
				@Override
				public void onFailure(Throwable t, String strMsg)
				{
				}

				@Override
				public void onSuccess(Object o)
				{
					System.out.println("安装量+1");
					SystemSettings.putBoolean(getApplicationContext(),
							"isInstall", false);
				}
			});
		}
	}
}
